package com.ambitor.grass.util.data;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DatasetResult extends DatasetList implements IDataset {
	
	private List names = new ArrayList();
	private int count;

	/**
	 * construct function
	 * @throws Exception
	 */
	public DatasetResult() throws Exception {
		super();
	}
	
	/**
	 * construct function
	 * @param rs
	 * @throws SQLException 
	 * @throws Exception
	 */
	public DatasetResult(ResultSet resultSet) throws SQLException{
		try {
			while (resultSet.next()) {
				ResultSetMetaData rsmd = resultSet.getMetaData();
				
				IData data = new DataMap();
				for (int i=1; i<=rsmd.getColumnCount(); i++) {
					String name = rsmd.getColumnName(i).toUpperCase();
					data.put(name, resultSet.getObject(i));
					
					if (resultSet.isFirst()) names.add(name);
				}
				add(data);
			}
			count = size();
		} catch (SQLException e) {
			throw e;
		}finally{
			Statement stmt = resultSet.getStatement();
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try {
					stmt.close();
				} catch (SQLException e) {
					throw e;
				}
			}
		}
	}
	
	/**
	 * get names
	 * @return String[]
	 */
	public String[] getNames() {
		return (String[]) names.toArray(new String[0]);
	}
	
	/**
	 * get count
	 * @return dint
	 */
	public int count() {
		return count;
	}
	/**
	 * set count
	 * @param count
	 */
	public void setCount(int count) {
		this.count = count;
	}
	
	/**
	 * clear
	 */
	public void clear() {
		super.clear();
		names = new ArrayList();
		this.count = 0;
	}
	
}